<template>
  <div class="office-pdf-viewer" :class="{ 'fullscreen': isFullscreen }">
    <div class="viewer-header">
      <div class="title">
        <i class="el-icon-document"></i>
        <span>{{ title || '文档预览' }}</span>
      </div>
      
      <div class="toolbar">
        <el-tooltip content="放大" placement="top">
          <el-button 
            size="mini" 
            icon="el-icon-zoom-in" 
            circle 
            @click="zoomIn"
          ></el-button>
        </el-tooltip>
        
        <el-tooltip content="缩小" placement="top">
          <el-button 
            size="mini" 
            icon="el-icon-zoom-out" 
            circle 
            @click="zoomOut"
          ></el-button>
        </el-tooltip>
        
        <el-tooltip content="重置缩放" placement="top">
          <el-button 
            size="mini" 
            icon="el-icon-refresh-right" 
            circle 
            @click="resetZoom"
          ></el-button>
        </el-tooltip>
        
        <el-divider direction="vertical"></el-divider>
        
        <el-tooltip content="全屏" placement="top">
          <el-button 
            size="mini" 
            :icon="isFullscreen ? 'el-icon-close' : 'el-icon-full-screen'" 
            circle 
            @click="toggleFullscreen"
          ></el-button>
        </el-tooltip>
        
        <el-tooltip content="下载" placement="top">
          <el-button 
            size="mini" 
            icon="el-icon-download" 
            circle 
            @click="downloadPdf"
            :disabled="!url"
          ></el-button>
        </el-tooltip>
        
        <el-tooltip content="新标签打开" placement="top">
          <el-button 
            size="mini" 
            icon="el-icon-share" 
            circle 
            @click="openInNewTab"
            :disabled="!url"
          ></el-button>
        </el-tooltip>
      </div>
    </div>
    
    <div class="viewer-content" ref="viewerContent">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-overlay">
        <el-progress 
          type="circle" 
          :percentage="loadingProgress" 
          :width="80"
          :stroke-width="6"
        ></el-progress>
        <p class="loading-text">{{ loadingText }}</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error-overlay">
        <i class="el-icon-warning-outline error-icon"></i>
        <p class="error-message">{{ errorMessage }}</p>
        <div class="error-actions">
          <el-button 
            type="primary" 
            size="small" 
            @click="reload"
            style="margin-right: 10px"
          >重试</el-button>
          <el-button 
            type="info" 
            size="small" 
            @click="openInNewTab"
          >新标签打开</el-button>
        </div>
      </div>
      
      <!-- PDF iframe容器 -->
      <div 
        v-else 
        class="iframe-container"
        :style="{ transform: `scale(${zoom})` }"
      >
        <iframe 
          v-if="url" 
          ref="pdfFrame"
          :src="processedUrl" 
          class="pdf-iframe"
          @load="handleIframeLoad"
          @error="handleIframeError"
          frameborder="0"
          width="100%"
          height="100%"
          allow="fullscreen"
        ></iframe>
        <div v-else class="no-document">
          <i class="el-icon-document"></i>
          <p>未指定文档</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/**
 * Office PDF预览组件
 * 使用iframe嵌入式方式预览PDF文档
 * 
 * Props:
 * - url: PDF文档URL
 * - title: 文档标题
 * - autoLoad: 是否自动加载文档
 */
export default {
  name: 'OfficePdfViewer',
  
  props: {
    // PDF文档URL
    url: {
      type: String,
      default: '',
      required: true
    },
    // 文档标题
    title: {
      type: String,
      default: '文档预览'
    },
    // 是否自动加载
    autoLoad: {
      type: Boolean,
      default: true
    },
    // 是否使用Google PDF查看器作为备选
    useGoogleViewer: {
      type: Boolean,
      default: false
    }
  },
  
  data() {
    return {
      // 加载状态
      loading: false,
      loadingProgress: 0,
      loadingText: '加载文档中...',
      loadingTimer: null,
      
      // 错误状态
      error: false,
      errorMessage: '文档加载失败，请检查URL或网络连接',
      
      // 缩放控制
      zoom: 1,
      zoomStep: 0.1,
      minZoom: 0.5,
      maxZoom: 2,
      
      // 全屏控制
      isFullscreen: false,
      
      // 原始文档URL
      originalUrl: '',
      
      // 重试次数
      retryCount: 0,
      maxRetries: 2,
      
      // 使用Google PDF查看器
      useGooglePdfViewer: false
    }
  },
  
  computed: {
    // 处理后的URL，解决跨域等问题
    processedUrl() {
      if (!this.url) return '';
      
      // 如果使用Google PDF查看器
      if (this.useGooglePdfViewer) {
        // 确保URL是完整路径
        const fullUrl = this.getFullUrl(this.url);
        return `https://docs.google.com/viewer?url=${encodeURIComponent(fullUrl)}&embedded=true`;
      }
      
      // 尝试直接使用浏览器内置PDF查看器
      return this.url;
    }
  },
  
  watch: {
    url: {
      handler(newUrl) {
        if (newUrl && this.autoLoad) {
          // 重置重试次数和Google查看器状态
          this.retryCount = 0;
          this.useGooglePdfViewer = this.useGoogleViewer;
          
          // 加载文档
          this.loadDocument(newUrl)
        }
      },
      immediate: true
    }
  },
  
  mounted() {
    // 监听ESC键退出全屏
    document.addEventListener('keydown', this.handleKeyDown)
    
    // 监听iframe加载错误
    window.addEventListener('error', this.handleGlobalError, true)
    
    // 如果有URL且设置了自动加载，初始化加载文档
    if (this.url && this.autoLoad) {
      this.loadDocument(this.url)
    }
  },
  
  beforeDestroy() {
    // 清除事件监听和定时器
    document.removeEventListener('keydown', this.handleKeyDown)
    window.removeEventListener('error', this.handleGlobalError, true)
    this.clearLoadingTimer()
  },
  
  methods: {
    /**
     * 加载文档
     */
    loadDocument(url) {
      if (!url) {
        this.handleError('未指定文档URL')
        return
      }
      
      this.originalUrl = url
      this.error = false
      this.startLoading()
    },
    
    /**
     * 开始加载动画
     */
    startLoading() {
      this.loading = true
      this.loadingProgress = 0
      this.clearLoadingTimer()
      
      // 模拟加载进度
      this.loadingTimer = setInterval(() => {
        if (this.loadingProgress < 90) {
          this.loadingProgress += Math.floor(Math.random() * 10) + 5
          this.loadingProgress = Math.min(this.loadingProgress, 90)
        }
      }, 300)
    },
    
    /**
     * 清除加载定时器
     */
    clearLoadingTimer() {
      if (this.loadingTimer) {
        clearInterval(this.loadingTimer)
        this.loadingTimer = null
      }
    },
    
    /**
     * 处理iframe加载完成事件
     */
    handleIframeLoad() {
      const iframe = this.$refs.pdfFrame
      
      // 清除加载计时器
      this.clearLoadingTimer()
      this.loadingProgress = 100
      
      // 延迟检查是否成功加载
      setTimeout(() => {
        try {
          // 检查iframe是否可访问
          if (iframe) {
            // 尝试通过检查iframe内容判断是否加载成功
            // 由于跨域限制，可能无法直接访问iframe内容
            // 我们假设加载完成
            this.loading = false
            this.$emit('loaded')
          } else {
            this.handleError('PDF加载失败')
          }
        } catch (e) {
          console.error('iframe访问错误', e)
          
          // 如果出现跨域错误但仍然显示内容，我们认为加载成功
          this.loading = false
          this.$emit('loaded')
        }
      }, 800)
    },
    
    /**
     * 处理iframe加载错误
     */
    handleIframeError() {
      this.handleRetry('文档加载失败，请检查URL或网络连接')
    },
    
    /**
     * 处理重试逻辑
     */
    handleRetry(message) {
      this.retryCount++
      
      // 如果重试次数小于最大重试次数，且没有使用Google PDF查看器
      if (this.retryCount <= this.maxRetries && !this.useGooglePdfViewer) {
        // 切换到Google PDF查看器模式
        this.useGooglePdfViewer = true
        
        // 重新加载
        this.clearLoadingTimer()
        this.startLoading()
        
        // 更新加载文本
        this.loadingText = '正在使用备用查看器加载...'
      } else {
        // 重试失败，显示错误
        this.handleError(message)
      }
    },
    
    /**
     * 处理错误
     */
    handleError(message) {
      this.clearLoadingTimer()
      this.loading = false
      this.error = true
      this.errorMessage = message
      
      this.$emit('error', message)
    },
    
    /**
     * 重新加载文档
     */
    reload() {
      // 重置重试计数
      this.retryCount = 0
      this.useGooglePdfViewer = this.useGoogleViewer
      
      // 重新加载
      this.loadDocument(this.originalUrl)
    },
    
    /**
     * 在新标签页中打开PDF
     */
    openInNewTab() {
      if (!this.originalUrl) {
        this.$message.warning('没有可打开的文档')
        return
      }
      
      window.open(this.originalUrl, '_blank')
    },
    
    /**
     * 缩放控制
     */
    zoomIn() {
      if (this.zoom < this.maxZoom) {
        this.zoom = parseFloat((this.zoom + this.zoomStep).toFixed(2))
      }
    },
    
    zoomOut() {
      if (this.zoom > this.minZoom) {
        this.zoom = parseFloat((this.zoom - this.zoomStep).toFixed(2))
      }
    },
    
    resetZoom() {
      this.zoom = 1
    },
    
    /**
     * 切换全屏模式
     */
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
      
      if (this.isFullscreen) {
        document.body.style.overflow = 'hidden'
      } else {
        document.body.style.overflow = ''
      }
      
      // 触发事件
      this.$emit('fullscreen-change', this.isFullscreen)
    },
    
    /**
     * 处理键盘事件
     */
    handleKeyDown(e) {
      // ESC键退出全屏
      if (e.key === 'Escape' && this.isFullscreen) {
        this.toggleFullscreen()
      }
    },
    
    /**
     * 下载PDF文档
     */
    downloadPdf() {
      if (!this.originalUrl) {
        this.$message.warning('没有可下载的文档')
        return
      }
      
      const link = document.createElement('a')
      link.href = this.originalUrl
      link.target = '_blank'
      link.download = this.title || 'document.pdf'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$emit('download')
    },
    
    /**
     * 处理全局错误事件，捕获iframe加载失败
     */
    handleGlobalError(event) {
      // 检查错误是否与当前iframe相关
      if (event.target && 
          (event.target === this.$refs.pdfFrame || 
           event.target.tagName === 'IFRAME')) {
        
        // 防止错误冒泡
        event.preventDefault()
        event.stopPropagation()
        
        // 如果未使用Google查看器，尝试切换
        if (!this.useGooglePdfViewer) {
          this.handleRetry('PDF加载过程中遇到错误')
        } else {
          this.handleError('PDF加载失败，请尝试其他方式打开')
        }
        
        return false
      }
    },
    
    /**
     * 获取完整URL路径
     */
    getFullUrl(url) {
      // 如果已经是完整URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      
      // 处理相对路径
      const baseUrl = window.location.origin;
      return `${baseUrl}/${url.replace(/^\//, '')}`;
    },
  }
}
</script>

<style scoped>
.office-pdf-viewer {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.office-pdf-viewer.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  border-radius: 0;
}

.viewer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  min-height: 40px;
}

.title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.title i {
  margin-right: 8px;
  color: #409EFF;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 4px;
}

.viewer-content {
  flex: 1;
  position: relative;
  overflow: auto;
  background-color: #f5f7fa;
}

.iframe-container {
  width: 100%;
  height: 100%;
  transform-origin: top center;
  transition: transform 0.2s ease;
}

.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background-color: white;
}

/* 加载和错误状态样式 */
.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  z-index: 10;
}

.loading-text,
.error-message {
  margin-top: 16px;
  font-size: 14px;
  color: #606266;
}

.error-icon {
  font-size: 48px;
  color: #F56C6C;
  margin-bottom: 8px;
}

.error-actions {
  margin-top: 16px;
  display: flex;
}

/* 无文档状态样式 */
.no-document {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.no-document i {
  font-size: 48px;
  margin-bottom: 16px;
}
</style> 